import bus from "@/utils/bus"

let worker = null

export function initWorker(token) {
    worker = import.meta.env.MODE === "development" ? new SharedWorker("./share.js") : new SharedWorker("../static/dist/share.js")
    worker.port.start()
    worker.port.postMessage({
        type: 'init',
        url: `${import.meta.env.VITE_APP_API_URL}/socket?token=${token}`,
    })

    worker.port.onmessage = (e) => {
        const reader = new FileReader()
        reader.readAsText(e.data, "utf-8")
        reader.onload = () => {
            const data = JSON.parse(reader.result)
            if (data.heart) {
                return
            }
            bus.emit("onmessage", data)
        }
    }
}

export function sendMessage(msg) {
    if (worker) {
        worker.port.postMessage({
            type: "sendMessage",
            msg
        })
    }
}

export function closeWorker() {
    if (worker) {
        worker.port.postMessage({
            type: "close"
        })
        worker = null
    }
}
